<?php

namespace app\api\controller;

use app\common\controller\Api;
use think\Request;
use think\Db;

/**
 * 示例接口
 */
class Login extends Api
{
    //如果$noNeedLogin为空表示所有接口都需要登录才能请求
    //如果$noNeedRight为空表示所有接口都需要验证权限才能请求
    //如果接口已经设置无需登录,那也就无需鉴权了
    //
    // 无需登录的接口,*表示全部
    protected $noNeedLogin = ['minprogram'];
    // 无需鉴权的接口,*表示全部
    protected $noNeedRight = ['test2'];

    /**
     * 小程序登陆
     * 
     */
  	public function minprogram($code,$nickname,$avatar){
        $wxAppID = config('wx.app_id');
      	$wxAppSecret = config('wx.app_secret');
        $wxLoginUrl = sprintf(config('wx.login_url'),$wxAppID, $wxAppSecret, $code);
        $result = curl_get($wxLoginUrl);
        $wxResult = json_decode($result, true);
      	
      	$userInfo = Db::table('xmr_user')->where('openid', $wxResult['openid'])->find();
      	if($userInfo){
        	return ['uid'=>$userInfo['id'],'nickname'=>$userInfo['nickname'],'avatar'=>$userInfo['avatar']];
        }else{
        	$user = new User();
          	return ['uid'=>$user->addUser($wxResult['openid'],$nickname,$avatar)];
        }
      	
    }
}